import React, { useState, useRef, useEffect } from 'react';
import {
    StyleSheet,
    View,
    Text,
    TextInput,
    TouchableOpacity,
    ScrollView,
    SafeAreaView,
    Alert
} from 'react-native';
import MqttClient, { ConnectionOptions, ClientEvent, MQTTEventHandler } from '@ko-developerhong/react-native-mqtt';
import Header from '../../../components/Header';

interface MessageCenterProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
}

const MessageCenter: React.FC<MessageCenterProps> = ({ onNavigateToLogin, onBackPress }) => {
    const [client, setClient] = useState<typeof MqttClient | null>(null);
    const [connectionStatus, setConnectionStatus] = useState<string>('未连接');
    const [messages, setMessages] = useState<string[]>([]);
    const [subscribeTopic, setSubscribeTopic] = useState<string>('test/topic');
    const [publishTopic, setPublishTopic] = useState<string>('test/topic');
    const [message, setMessage] = useState<string>('');
    const [host, setHost] = useState<string>('121.229.204.80');
    const [port, setPort] = useState<string>('1883');
    const [isConnecting, setIsConnecting] = useState<boolean>(false);
    const isManualDisconnectRef = useRef<boolean>(false);
    const scrollViewRef = useRef<ScrollView>(null);

    // 当消息更新时自动滚动到底部
    useEffect(() => {
        if (scrollViewRef.current && messages.length > 0) {
            setTimeout(() => {
                scrollViewRef.current?.scrollToEnd({ animated: true });
            }, 100);
        }
    }, [messages]);

    // 组件卸载时断开连接
    useEffect(() => {
        return () => {
            if (client && connectionStatus === '已连接') {
                MqttClient.disconnect();
            }
        };
    }, [client, connectionStatus]);

    // 连接MQTT服务器
    const connectMQTT = async () => {
        if (isConnecting) return;

        setIsConnecting(true);
        setConnectionStatus('连接中...');
        setMessages(prev => [...prev, '正在连接 MQTT 服务器...']);

        try {
            const mqttClientId = `mqtt-client-${Date.now()}`;
            const finalHost = host;
            const finalPort = parseInt(port, 10);
            const url = `mqtt://${finalHost}:${finalPort}`;
            // 设置连接选项
            const options: ConnectionOptions = {
                clientId: mqttClientId,
                cleanSession: true,
                keepAlive: 60,
                timeout: 30,
                maxInFlightMessages: 1,
                autoReconnect: false,
                enableSsl: false,
                protocol: 'mqtt'
            };


            // 设置事件监听器
            const onConnect: MQTTEventHandler<ClientEvent.Connect> = (reconnect) => {
                setConnectionStatus('已连接');
                setIsConnecting(false);
                setMessages(prev => [...prev, 'MQTT 连接成功！']);
                setClient(MqttClient);
            };

            const onMessage: MQTTEventHandler<ClientEvent.Message> = (topic, message) => {
                setMessages(prev => [...prev, `收到消息: ${message.toString()} [主题: ${topic}]`]);
            };

            const onError: MQTTEventHandler<ClientEvent.Error> = (error) => {
                // 如果是手动断开连接，忽略错误
                if (isManualDisconnectRef.current) {
                    return;
                }

                console.error('MQTT 错误:', error);
                setConnectionStatus('连接失败');
                setIsConnecting(false);
                setMessages(prev => [...prev, `连接失败: ${error}`]);
            };

            const onDisconnect: MQTTEventHandler<ClientEvent.Disconnect> = (cause) => {

                // 只有在非手动断开时才更新状态（手动断开已经在 disconnectMQTT 中处理了）
                if (cause !== 'User disconnected') {
                    setConnectionStatus('未连接');
                    setIsConnecting(false);
                    setMessages(prev => [...prev, `连接已断开: ${cause}`]);
                }
            };

            // 先移除所有事件监听器，避免重复注册
            MqttClient.off(ClientEvent.Connect);
            MqttClient.off(ClientEvent.Message);
            MqttClient.off(ClientEvent.Error);
            MqttClient.off(ClientEvent.Disconnect);

            // 注册事件监听器
            MqttClient.on(ClientEvent.Connect, onConnect);
            MqttClient.on(ClientEvent.Message, onMessage);
            MqttClient.on(ClientEvent.Error, onError);
            MqttClient.on(ClientEvent.Disconnect, onDisconnect);

            // 发起连接
            await MqttClient.connect(url, options);

            setClient(MqttClient);

        } catch (error: any) {
            console.error('连接异常:', error);
            setConnectionStatus('连接失败');
            setIsConnecting(false);
            setMessages(prev => [...prev, `连接异常: ${error.message}`]);
        }
    };

    // 断开连接
    const disconnectMQTT = () => {
        if (client) {
            // 设置手动断开标志
            isManualDisconnectRef.current = true;

            // 先设置状态，避免被事件覆盖
            setConnectionStatus('未连接');
            setIsConnecting(false);
            setMessages(prev => [...prev, '已断开连接']);
            setClient(null);

            // 然后断开连接
            MqttClient.disconnect();

            // 延迟重置标志，确保事件处理完成
            setTimeout(() => {
                isManualDisconnectRef.current = false;
            }, 1000);
        }
    };

    // 发布消息
    const publishMessage = () => {
        if (client && message && publishTopic) {
            try {
                MqttClient.publish(publishTopic, message, 0, false);
                setMessages(prev => [...prev, `发送: ${message} [到: ${publishTopic}]`]);
                setMessage('');
            } catch (error) {
                setMessages(prev => [...prev, `发布失败: ${error}`]);
            }
        } else {
            Alert.alert('提示', '请先连接并输入消息和发布主题');
        }
    };

    // 订阅主题
    const subscribeToTopic = () => {
        if (client && subscribeTopic) {
            try {
                MqttClient.subscribe(subscribeTopic, 0);
                setMessages(prev => [...prev, `已订阅主题: ${subscribeTopic}`]);
            } catch (error) {
                setMessages(prev => [...prev, `订阅失败: ${error}`]);
            }
        } else {
            Alert.alert('提示', '请先连接并输入订阅主题');
        }
    };

    // 取消订阅
    const unsubscribeFromTopic = () => {
        if (client && subscribeTopic) {
            try {
                MqttClient.unsubscribe([subscribeTopic]);
                setMessages(prev => [...prev, `已取消订阅: ${subscribeTopic}`]);
            } catch (error) {
                setMessages(prev => [...prev, `取消订阅失败: ${error}`]);
            }
        }
    };
    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="消息中心"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />
            <ScrollView style={styles.scrollContainer} showsVerticalScrollIndicator={true}>

                <View style={[styles.connectionStatus,
                { backgroundColor: connectionStatus === '已连接' ? '#d4edda' : '#f8d7da' }]}>
                    <Text>连接状态: {connectionStatus}</Text>
                </View>

                <View style={styles.inputContainer}>
                    <Text style={styles.sectionTitle}>服务器配置</Text>
                    <TextInput
                        style={styles.input}
                        value={host}
                        onChangeText={setHost}
                        placeholder="MQTT服务器地址"
                    />

                    <TextInput
                        style={styles.input}
                        value={port}
                        onChangeText={setPort}
                        placeholder="端口"
                        keyboardType="numeric"
                    />

                    <Text style={styles.sectionTitle}>订阅主题</Text>
                    <TextInput
                        style={styles.input}
                        value={subscribeTopic}
                        onChangeText={setSubscribeTopic}
                        placeholder="订阅主题"
                    />

                    <Text style={styles.sectionTitle}>发布消息</Text>
                    <TextInput
                        style={styles.input}
                        value={publishTopic}
                        onChangeText={setPublishTopic}
                        placeholder="发布主题"
                    />

                    <TextInput
                        style={styles.input}
                        value={message}
                        onChangeText={setMessage}
                        placeholder="消息内容"
                    />
                </View>

                <View style={styles.buttonContainer}>
                    <TouchableOpacity
                        style={[
                            styles.button,
                            connectionStatus === '已连接' ? styles.disconnectButton :
                                isConnecting ? styles.connectingButton : styles.connectButton
                        ]}
                        onPress={connectionStatus === '已连接' ? disconnectMQTT : connectMQTT}
                        disabled={isConnecting}
                    >
                        <Text style={styles.buttonText}>
                            {isConnecting ? '连接中...' : connectionStatus === '已连接' ? '断开连接' : '连接'}
                        </Text>
                    </TouchableOpacity>

                    <TouchableOpacity
                        style={[styles.button, styles.publishButton]}
                        onPress={publishMessage}
                    >
                        <Text style={styles.buttonText}>发布消息</Text>
                    </TouchableOpacity>

                    <TouchableOpacity
                        style={[styles.button, styles.subscribeButton]}
                        onPress={subscribeToTopic}
                    >
                        <Text style={styles.buttonText}>订阅主题</Text>
                    </TouchableOpacity>

                    <TouchableOpacity
                        style={[styles.button, styles.unsubscribeButton]}
                        onPress={unsubscribeFromTopic}
                    >
                        <Text style={styles.buttonText}>取消订阅</Text>
                    </TouchableOpacity>
                </View>

                <View style={styles.messagesContainer}>
                    <Text style={styles.messagesTitle}>消息日志</Text>
                    <ScrollView
                        ref={scrollViewRef}
                        style={styles.messagesScrollView}
                        showsVerticalScrollIndicator={true}
                        onContentSizeChange={() => {
                            scrollViewRef.current?.scrollToEnd({ animated: true });
                        }}
                    >
                        {messages.map((msg, index) => (
                            <Text key={index} style={styles.message}>{msg}</Text>
                        ))}
                    </ScrollView>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    scrollContainer: {
        flex: 1,
        padding: 10,
    },

    connectionStatus: {
        padding: 10,
        borderRadius: 5,
        marginBottom: 15,
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#c3e6cb',
    },
    inputContainer: {
        marginBottom: 15,
    },
    sectionTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
        marginTop: 10,
        marginBottom: 5,
    },
    input: {
        height: 40,
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 5,
        paddingHorizontal: 10,
        marginBottom: 10,
        backgroundColor: 'white',
    },
    buttonContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: 'space-between',
        marginBottom: 15,
    },
    button: {
        padding: 12,
        borderRadius: 5,
        minWidth: '48%',
        alignItems: 'center',
        marginBottom: 10,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 2,
        elevation: 2,
    },
    connectButton: {
        backgroundColor: '#28a745',
    },
    connectingButton: {
        backgroundColor: '#ffc107',
    },
    disconnectButton: {
        backgroundColor: '#dc3545',
    },
    publishButton: {
        backgroundColor: '#007bff',
    },
    subscribeButton: {
        backgroundColor: '#17a2b8',
    },
    unsubscribeButton: {
        backgroundColor: '#6c757d',
    },
    buttonText: {
        color: 'white',
        fontWeight: 'bold',
    },
    messagesContainer: {
        height: 200,
        borderColor: '#ccc',
        borderWidth: 1,
        marginBottom: 20,
        borderRadius: 5,
        backgroundColor: 'white',
    },
    messagesTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
        padding: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        backgroundColor: '#f8f9fa',
    },
    messagesScrollView: {
        flex: 1,
        padding: 10,
    },
    message: {
        paddingVertical: 5,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        fontSize: 14,
        color: '#333',
    },
});

export default MessageCenter; 